package com.xiaoyu.merchant.ui.fragment.commodity;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.techfansy.utils.PermissionUtils;
import com.xiaoyu.commonlib.network.CommonHttpResponser;
import com.xiaoyu.commonlib.ui.adapter.AllPowerfulAdapter;
import com.xiaoyu.commonlib.utils.PreferencesUtil;
import com.xiaoyu.commonlib.utils.ToastUtil;
import com.xiaoyu.merchant.MerchantConstants;
import com.xiaoyu.merchant.R;
import com.xiaoyu.merchant.model.PutawaySoldBean;
import com.xiaoyu.merchant.network.NetworkManager;
import com.xiaoyu.merchant.ui.activity.commodity.CommodityDetailActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author jx
 * @date 创建时间 2018/12/29
 * @Description 已上架
 */
public class PutawayFragment extends Fragment {
    private View mView;
    private AllPowerfulAdapter mAdapter;
    @BindView(R.id.common_recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.common_recycler_view_empty_page)
    ImageView mEmptyPage;//空页面
    @BindView(R.id.smart_refresh_layout)
    SmartRefreshLayout smartRefreshLayout;
    private int page = 1;//当前页数
    private int totalPage;//总页数
    private List<PutawaySoldBean.DataBean.ListBean> mBeanList = new ArrayList<>();

    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (mView == null) {
            mView = inflater.inflate(R.layout.common_recycler_view, container, false);
            //绑定fragment
            ButterKnife.bind(this, mView);
            initView();
        }
        ViewGroup parent = (ViewGroup) mView.getParent();
        if (parent != null) {
            parent.removeView(mView);
        }
        return mView;

    }

    private void initView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setBackgroundColor(getResources().getColor(R.color.color_gray_F3));
        smartRefreshLayout.setOnRefreshListener(onRefreshListener);
        smartRefreshLayout.setOnLoadMoreListener(onLoadMoreListener);
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @NonNull
            @Override
            public RefreshFooter createRefreshFooter(@NonNull Context context, @NonNull RefreshLayout layout) {
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @NonNull
            @Override
            public RefreshHeader createRefreshHeader(@NonNull Context context, @NonNull RefreshLayout layout) {
                return new ClassicsHeader(context).setDrawableSize(20);
            }
        });
        setAdapter(mBeanList);
    }

    @Override
    public void onResume() {
        super.onResume();
        page = 1;
        mBeanList.clear();
        getPutAwayList();
    }

    //接口获取上架商品
    private void getPutAwayList() {
        NetworkManager.putawaySold(PreferencesUtil.getString(PreferencesUtil.TOKEN, ""), "1", page, new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                succeedPutAway(result);
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {

            }
        });
    }

    private void succeedPutAway(String result) {
        if (page == 1) {
            mBeanList.clear();
        }
        PutawaySoldBean bean = new Gson().fromJson(result, PutawaySoldBean.class);
        mBeanList.addAll(bean.getData().getList());
        totalPage = Integer.parseInt(bean.getData().getCount());
        if (mBeanList.size() == 0) {
            mEmptyPage.setVisibility(View.VISIBLE);
            mRecyclerView.setVisibility(View.GONE);
            mEmptyPage.setImageResource(R.mipmap.no_data);
            smartRefreshLayout.setEnableRefresh(false);
            smartRefreshLayout.setEnableLoadMore(false);
        }
        mAdapter.notifyDataSetChanged();
        if (totalPage <= 1) {
            smartRefreshLayout.setEnableLoadMore(false);
        } else {
            smartRefreshLayout.setEnableLoadMore(true);
        }
        setAdapter(mBeanList);
    }

    //设置适配器显示数据
    private void setAdapter(final List<PutawaySoldBean.DataBean.ListBean> mPutSoldList) {
        mAdapter = new AllPowerfulAdapter<PutawaySoldBean.DataBean.ListBean>(R.layout.putaway_item, mPutSoldList, new AllPowerfulAdapter.OnClickListener<PutawaySoldBean.DataBean.ListBean>() {
            @Override
            public void setOnClick(BaseViewHolder baseViewHolder, PutawaySoldBean.DataBean.ListBean listBean, int position) {
                //item点击事件跳转详情页面
                Intent intent = new Intent(getActivity(), CommodityDetailActivity.class);
                intent.putExtra(MerchantConstants.GOODS_ID, mPutSoldList.get(position).getGoodsid());//商品id
                startActivity(intent);
            }
        }) {
            @Override
            protected void convert(BaseViewHolder baseViewHolder, final PutawaySoldBean.DataBean.ListBean listBean) {
                super.convert(baseViewHolder, listBean);
                baseViewHolder.setText(R.id.putaway_name, listBean.getGoodsname());
                ImageView goodsImg = baseViewHolder.getView(R.id.putaway_img);
                Glide.with(getActivity()).load(listBean.getGoodsimg()).into(goodsImg);
                baseViewHolder.setText(R.id.putaway_price, "¥  " + listBean.getGoodsprice1());

                TextView mSoldOut = baseViewHolder.getView(R.id.sold_out);
                mSoldOut.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        soldOut(listBean.getGoodsid());
                    }
                });
            }
        };
        mRecyclerView.setAdapter(mAdapter);
    }

    private void soldOut(String goodsid) {
        NetworkManager.upDownFrame(PreferencesUtil.getString(PreferencesUtil.TOKEN, ""), goodsid, "2", new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                ToastUtil.showToast(getActivity(), "下架商品成功");
                getPutAwayList();
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {

            }
        });
    }

    /**
     * 数据刷新
     */
    private OnRefreshListener onRefreshListener = new OnRefreshListener() {
        @Override
        public void onRefresh(@NonNull RefreshLayout refreshLayout) {
            page = 1;
            mBeanList.clear();
            mAdapter.notifyDataSetChanged();
            getPutAwayList();
            smartRefreshLayout.finishRefresh();
            smartRefreshLayout.setNoMoreData(false);
        }
    };


    /**
     * 加载更多
     */
    private OnLoadMoreListener onLoadMoreListener = new OnLoadMoreListener() {
        @Override
        public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
            if (page < totalPage) {
                page = page + 1;
                getPutAwayList();
                smartRefreshLayout.finishLoadMore();
                smartRefreshLayout.setNoMoreData(true);
            } else {
                ToastUtil.showToast(getActivity(), "已经没有更多数据！");
                smartRefreshLayout.finishLoadMore();
                smartRefreshLayout.setNoMoreData(false);
                smartRefreshLayout.finishLoadMoreWithNoMoreData();
            }
        }
    };

}
